import type { PiniaPluginContext, StateTree } from 'pinia';

type StorageType = 'localStorage' | 'sessionStorage';
type PersistOptions = {
  key?: string;
  storage?: StorageType;
  paths?: string[];
};

/*
 * @description: pinia 插件
 * @return {void}
 * */
const piniaPersist = () => {
  return (context: PiniaPluginContext) => {
    const { store, options } = context;
    const persistOptions = options.persist as PersistOptions | undefined;

    if (!persistOptions) return;

    const { key = store.$id, storage = 'localStorage', paths } = persistOptions;

    // 从存储中恢复状态
    try {
      const storageData = window[storage].getItem(key);
      if (storageData) {
        const parsedData = JSON.parse(storageData);
        store.$patch(parsedData);
      }
    } catch (error) {
      console.error('Persisted state restoration failed:', error);
    }

    // 监听变化并持久化状态
    store.$subscribe((_, state) => {
      const stateToPersist = paths
        ? paths.reduce((obj, path) => {
            obj[path] = store.$state[path];
            return obj;
          }, {} as StateTree)
        : state;

      try {
        window[storage].setItem(key, JSON.stringify(stateToPersist));
      } catch (error) {
        console.error('Persisted state storage failed:', error);
      }
    });
  };
};

export default piniaPersist;
